//
//  RegisterConfigViewController.m
//  location
//
//  Created by Dongxiang Xu on 2025/10/31.
//

#import "RegisterConfigViewController.h"
#import "XDXBaseTabBarViewController.h"
#import "UIImageView+WebCache.h"
#import "UIImagePickerController+ST.h"
#import "HQImageEditViewController.h"

@interface RegisterConfigViewController ()<UIImagePickerControllerDelegate, UINavigationControllerDelegate,HQImageEditViewControllerDelegate>

@property (nonatomic,strong) UIImageView *avatar;
@property (nonatomic,strong) UITextField *textField;

@end

@implementation RegisterConfigViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.view.backgroundColor = RealWhiteColor;
    self.navigationItem.hidesBackButton = YES;
    [self initView];
    [self getUserInfo];
}

- (void)initView
{
    UILabel *hello = [[UILabel alloc] initWithFrame:CGRectMake(16, STATUSHEIGHT+30, SCREEN_WIDTH-32, 26)];
    hello.text = @"你好 👋 ";
    hello.textColor = GraryLightColor;
    hello.font = MEDIUM_FONT(16);
    [self.view addSubview:hello];
    
    UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(16, hello.maxY+4, SCREEN_WIDTH-32, 26)];
    title.font = MEDIUM_FONT(24);
    title.textColor = RealBlackColor;
    title.text = @"设置头像和昵称";
    [self.view addSubview:title];
    
    _avatar = [[UIImageView alloc] initWithFrame:CGRectMake((SCREEN_WIDTH-104)/2, title.maxY+50, 104, 104)];
    _avatar.userInteractionEnabled = YES;
    _avatar.layer.masksToBounds = YES;
    [_avatar.layer setCornerRadius:52];
    [self.view addSubview:_avatar];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] init];
    [[tap rac_gestureSignal] subscribeNext:^(id x) {
        [self album];
    }];
    [_avatar addGestureRecognizer:tap];
    
    UIImageView *photo = [[UIImageView alloc] initWithFrame:CGRectMake(_avatar.x+67, _avatar.y+67, 37, 37)];
    photo.image = [UIImage imageNamed:@"photo_album"];
    [self.view addSubview:photo];
    
    UIView *nickView = [[UIView alloc] initWithFrame:CGRectMake(48, _avatar.maxY+30, SCREEN_WIDTH-96, 52)];
    nickView.backgroundColor = [GraryMiddleColor colorWithAlphaComponent:0.4];
    nickView.layer.masksToBounds = YES;
    [nickView.layer setCornerRadius:16];
    [self.view addSubview:nickView];
    
    _textField = [[UITextField alloc] initWithFrame:CGRectMake(16, 0, nickView.width-32, nickView.height)];
    _textField.clearButtonMode = UITextFieldViewModeWhileEditing;
    _textField.textColor = BlackColor;
    _textField.font = MEDIUM_FONT(14);
    _textField.tintColor = NormalMainColor;
    [_textField addTarget:self action:@selector(textChangeEvent:) forControlEvents:UIControlEventEditingChanged];
    [nickView addSubview:_textField];
        
    UIButton *next = [[UIButton alloc] initWithFrame:CGRectMake(44, SCREEN_HEIGHT-142, SCREEN_WIDTH-88, 54)];
    next.backgroundColor = NormalMainColor;
    [next.layer setCornerRadius:27];
    next.layer.masksToBounds = YES;
    [next setTitle:@"继续" forState:UIControlStateNormal];
    [next.titleLabel setFont:REAL_MEDIUM_FONT(17)];
    [self.view addSubview:next];
    [[next rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        if (self.textField.text.length>0) {
            NSDictionary *param = [NSMutableDictionary dictionary];
            [param setValue:[XDXShareInstance shareInstance].userId forKey:@"userId"];
            [param setValue:self.textField.text forKey:@"nickName"];
            CryptoHTTPKit *manager = [[CryptoHTTPKit alloc] init];
            [manager encryptedPUT:@"/system/user/modify"
            parameters:param
            success:^(NSDictionary *responseObject) {
                XDXBaseTabBarViewController *tb = [[XDXBaseTabBarViewController alloc] init];
                [UIApplication sharedApplication].keyWindow.rootViewController = tb;
                [[UIApplication sharedApplication].keyWindow makeKeyAndVisible];
            }
            failure:^(NSError *aError) {
                
            }];
        }else{
            XDXBaseTabBarViewController *tb = [[XDXBaseTabBarViewController alloc] init];
            [UIApplication sharedApplication].keyWindow.rootViewController = tb;
            [[UIApplication sharedApplication].keyWindow makeKeyAndVisible];
        }
    }];
    
    UIButton *ignore = [[UIButton alloc] initWithFrame: CGRectMake(44, next.maxY+16, SCREEN_WIDTH-88, 22)];
    [ignore setTitle:@"先不设置" forState:UIControlStateNormal];
    [ignore.titleLabel setFont:DEFAULT_FONT(15)];
    [ignore setTitleColor:GraryLightColor forState:UIControlStateNormal];
    [self.view addSubview:ignore];
    [[ignore rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        XDXBaseTabBarViewController *tb = [[XDXBaseTabBarViewController alloc] init];
        [UIApplication sharedApplication].keyWindow.rootViewController = tb;
        [[UIApplication sharedApplication].keyWindow makeKeyAndVisible];
    }];
}

- (void)getUserInfo
{

    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    CryptoHTTPKit *manager = [[CryptoHTTPKit alloc] init];
    [manager encryptedPOST:@"/system/user/getInfo"
    parameters:param
    success:^(NSDictionary *responseObject) {
        if ([responseObject[@"code"] integerValue]==200) {
            [self.avatar sd_setImageWithURL:[NSURL URLWithString:responseObject[@"data"][@"avatar"]]];
            self.textField.placeholder = responseObject[@"data"][@"nickName"];
            [XDXShareInstance shareInstance].userId = responseObject[@"data"][@"userId"];
        }
    }
    failure:^(NSError *aError) {
        
    }];
}

- (void)textChangeEvent:(UITextField *)textField
{
    if (textField.text.length>=10) {
        textField.text = [textField.text substringToIndex:10];
    }
}

- (void)album
{
    UIImagePickerController *controller = [UIImagePickerController imagePickerControllerWithSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
    [controller setDelegate:self];
    if ([controller isAvailablePhotoLibrary]) {
        [self presentViewController:controller animated:YES completion:nil];
    }
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    [self dismissViewControllerAnimated:YES completion:^{
        UIImage *imageOriginal = [info objectForKey:UIImagePickerControllerOriginalImage];
        HQImageEditViewController *vc = [[HQImageEditViewController alloc] init];
        vc.originImage = [self fixOrientationWithImage:imageOriginal];
        vc.delegate = self;
        vc.maskViewAnimation = YES;
        [self presentViewController:vc animated:YES completion:nil];
    }];
}

- (UIImage *)fixOrientationWithImage:(UIImage *)image
{

    // No-op if the orientation is already correct
    if (image.imageOrientation == UIImageOrientationUp) return image;

    // We need to calculate the proper transformation to make the image upright.
    // We do it in 2 steps: Rotate if Left/Right/Down, and then flip if Mirrored.
    CGAffineTransform transform = CGAffineTransformIdentity;

    switch (image.imageOrientation) {
        case UIImageOrientationDown:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, image.size.width, image.size.height);
            transform = CGAffineTransformRotate(transform, M_PI);
            break;

        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
            transform = CGAffineTransformTranslate(transform, image.size.width, 0);
            transform = CGAffineTransformRotate(transform, M_PI_2);
            break;

        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, 0, image.size.height);
            transform = CGAffineTransformRotate(transform, -M_PI_2);
            break;
    }

    switch (image.imageOrientation) {
        case UIImageOrientationUpMirrored:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, image.size.width, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;

        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, image.size.height, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
    }

    // Now we draw the underlying CGImage into a new context, applying the transform
    // calculated above.
    CGContextRef ctx = CGBitmapContextCreate(NULL, image.size.width, image.size.height,
                                             CGImageGetBitsPerComponent(image.CGImage), 0,
                                             CGImageGetColorSpace(image.CGImage),
                                             CGImageGetBitmapInfo(image.CGImage));
    CGContextConcatCTM(ctx, transform);
    switch (image.imageOrientation) {
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            // Grr...
            CGContextDrawImage(ctx, CGRectMake(0,0,image.size.height,image.size.width), image.CGImage);
            break;

        default:
            CGContextDrawImage(ctx, CGRectMake(0,0,image.size.width,image.size.height), image.CGImage);
            break;
    }

    // And now we just create a new UIImage from the drawing context
    CGImageRef cgimg = CGBitmapContextCreateImage(ctx);
    UIImage *img = [UIImage imageWithCGImage:cgimg];
    CGContextRelease(ctx);
    CGImageRelease(cgimg);
    return img;
}

- (void)saveImage:(UIImage *)image
{
    UIImage *saveImage = [self compressImage:image toSize:CGSizeMake(200, 200)];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
    NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent: [NSString stringWithFormat:@"avatarfile.png"]];
    BOOL result = [UIImagePNGRepresentation(saveImage) writeToFile:filePath atomically:YES];
    if (result == YES) {
        NSLog(@"保存成功");
        self.avatar.image = saveImage;
        [self uploadWithUrl:[NSURL fileURLWithPath:filePath]];
    }
}

- (UIImage *)compressImage:(UIImage *)image toSize:(CGSize)size
{
  UIGraphicsBeginImageContext(size);
  [image drawInRect:CGRectMake(0, 0, size.width, size.height)];
  UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();
  return scaledImage;
}


- (void)editController:(HQImageEditViewController *)vc finishiEditShotImage:(UIImage *)image originSizeImage:(UIImage *)originSizeImage
{
    [self saveImage:originSizeImage];
    [vc dismissViewControllerAnimated:YES completion:nil];
}

- (void)editControllerDidClickCancel:(HQImageEditViewController *)vc
{
    [vc dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)uploadWithUrl:(NSURL *)url
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.requestSerializer.timeoutInterval = 10;
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/html",@"image/jpeg",@"image/png",@"application/octet-stream",@"text/json",nil];
    [manager POST:[NSString stringWithFormat:@"%@/system/user/profile/avatar",NETURL] parameters:nil headers:@{@"Authorization":[XDXShareInstance shareInstance].access_token} constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
      
        NSData *fileData = [NSData dataWithContentsOfURL:url];
        [formData appendPartWithFileData:fileData name:@"avatarfile" fileName:[[NSString stringWithFormat:@"%@",[XDXShareInstance shareInstance].userId] stringByAppendingString:@".png"] mimeType:@"png"];

    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
       
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}


@end
